package cn.com.utt.unms.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;

import cn.com.utt.common.alipay.util.UtilDate;
import cn.com.utt.common.util.GraphicsMagickUtil;
import cn.com.utt.common.util.ImageUtil;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.unms.mapper.AdMapper;
import cn.com.utt.unms.mapper.AuthPageMapper;
import cn.com.utt.unms.mapper.PageListMapper;
import cn.com.utt.unms.pojo.Ad;
import cn.com.utt.unms.pojo.Page;
import cn.com.utt.unms.pojo.PageList;
import cn.com.utt.unms.service.AuthPageService;
import cn.com.utt.unms.utils.MapUtil;
import cn.com.utt.unms.vo.ImageUploadInfo;

@Service("authPageService")
public class AuthPageServiceImpl implements AuthPageService {
	@Autowired
	private AuthPageMapper authPageMapper;
	@Autowired
	private AdMapper adMapper;
	@Autowired
	private PageListMapper pageListMapper;
	@Value("${templates}")
	private String templates;
	@Value("${pagePaths}")
	private String pagePaths;
	@Value("${pageTitle}")
	private String pageTitles;
	@Value("${tempPath}")
	private String temp;
	@Value("${adPath}")
	private String adPath;
	@Value("${uploadPath}")
	private String uploadPath;

	@Override
	public TableOutput<PageList> queryAuthPageList(TableInput input, Long userId) {
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("userId", userId);
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());

		List<PageList> pageList = pageListMapper.queryByCondition(conditions);
		int total = pageListMapper.countByCondition(conditions);
		TableOutput<PageList> output = new TableOutput<>();
		output.setList(pageList);
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		return output;
	}

	@Override
	public void copyFile(File source, File target) {
		try {
			FileInputStream fstream = null;
			FileOutputStream out = null;
			try {
				fstream = new FileInputStream(source);
				out = new FileOutputStream(target.toString());
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = fstream.read(b)) != -1) {
					out.write(b, 0, len);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// throw new BusinessException("copyFile 发生异常", e);
			} finally {
				if (fstream != null) {
					fstream.close();
				}
				if (out != null) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// throw new BusinessException("copyFile 发生异常", e);
		}

	}

	public void copyFile(File source, File target, String pageTitle) {
		try {
			FileOutputStream fos = null;
			OutputStreamWriter osw = null;
			try {
				Document doc = Jsoup.parse(source, "utf-8");
				doc.title(pageTitle);
				fos = new FileOutputStream(target, false);
				osw = new OutputStreamWriter(fos, "UTF-8");
				HtmlCompressor compressor = new HtmlCompressor();
				compressor.setRemoveIntertagSpaces(true);
				String compressedHtml = compressor.compress(doc.html());
				osw.write(compressedHtml);

			} finally {
				if (osw != null) {
					osw.close();
				}
				if (fos != null) {
					fos.close();
				}
			}
		} catch (Exception e) {
		}

	}

	@Override
	public RestResult delAuthPages(List<Long> pageIds, Long userId) {
		RestResult result = new RestResult();
		List<Page> temps1 = authPageMapper.queryPageByPageListId(pageIds);
		if (temps1.size() > 0 && temps1 != null) {
			for (Page temp : temps1) {
				if (temp.getTmId() == 10000001 || temp.getTmId() == 10000003) {
					delAuthPages(temp.getId() + 1, userId);
				}
				delAuthPages(temp.getId(), userId);
			}
			pageListMapper.del(pageIds);
			result.setErrorCode(0);
			result.setErrorMsg("删除成功！");
		} else {
			result.setErrorCode(1);
			result.setErrorMsg("删除失败！");
		}

		return result;
	}

	public void delAuthPages(long pageId, long userId) {
		Page page = authPageMapper.queryPageById(pageId);
		if (page != null) {
			// if (!userPageId.equals(page.getId())) {
			String path = pagePaths + userId + File.separator + page.getPath();
			authPageMapper.delPage(page.getId());
			File file = new File(path);
			if (file.isFile() && file.exists()) {
				file.delete();
			} else {
				deleteDirectory(path);
			}
			// }
		}
	}

	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	private boolean deleteDirectory(String sPath) {
		boolean flag = true;
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	private boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	@Override
	public RestResult loadUserDefinedPage(Long pageListId, Long userId) {
		RestResult result = new RestResult();
		Byte pagetype = (byte) 0;
		String content = "";
		try {
			if (pageListId <= 0) {
				result.setErrorCode(1);
				result.setErrorMsg("参数错误");
				return result;
			} else {
				// 1.判断页面是否属于商家,是否是自定义页面,不属于则返回
				// 2.文件存在,则查询页面内容,不存在则返回
				// 3.如果页面来自代理商，查询页面广告位信息
				List<Page> pageList = authPageMapper.queryPageByPageListId(new ArrayList<Long>() {
					{
						add(pageListId);
					}
				});
				List<MapUtil> mapList = new ArrayList<>();
				for (Page page2 : pageList) {
					if (page2 != null && page2.getTmId().longValue() > 10000000) {
						pagetype = (byte) (page2.getTmId() - 10000000);
						String path = pagePaths + userId + File.separator + page2.getPath();
						File file = new File(path);
						if (file.exists()) {
							Document doc = Jsoup.parse(file, "utf-8");
							if (pagetype > (byte) 2) {
								content = doc.select(".box").html();
							} else {
								content = doc.select(".box").html();
							}
							MapUtil map = new MapUtil();
							map.setContent(content);
							map.setType(pagetype);
							mapList.add(map);
						} else {
							result.setErrorCode(1);
							result.setErrorMsg("文件加载错误");
							return result;
						}
					} else {
						result.setErrorCode(1);
						result.setErrorMsg("页面加载错误");
						return result;
					}

				}
				result.put("list", mapList);
				// Page page=authPageMapper.queryPageById(pageId);
				// if(page!=null&&page.getUserId().equals(userId)&&
				// page.getTmId().longValue() > 10000000){
				// System.out.println("if-------");
				// pagetype = (byte) (page.getTmId() - 10000000);
				// String path=pagePaths+userId+File.separator+page.getPath();
				// System.out.println("path: "+path);
				// File file = new File(path);
				// System.out.println("file isExist: "+file.exists());
				// if(file.exists()){
				// Document doc = Jsoup.parse(file, "utf-8");
				// if (pagetype > 2 && pagetype<5) {
				// content = doc.select(".box").html();
				// } else {
				// content = doc.select(".box").html();
				// }
				// result.put("content", content);
				// result.setErrorMsg("加载成功");
				// }else{
				// result.setErrorCode(1);
				// result.setErrorMsg("文件加载错误");
				// return result;
				// }
				// }else{
				// result.setErrorCode(1);
				// result.setErrorMsg("页面加载错误");
				// return result;
				// }
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(1);
			result.setErrorMsg("页面加载异常");
			return result;
		}
		return result;
	}

	@Override
	public RestResult uploadImage(MultipartFile multipartfile, String type) {
		RestResult res = new RestResult();
		String path = null;
		long maximumSize = 2097152;
		int pcType = 0;//
		try {
			// File file = new File(upload);
			if (multipartfile.isEmpty()) {
				res.setErrorCode(1);
				res.setErrorMsg("文件大小超出限制");
				return res;
			}
			if (multipartfile.getBytes().length > maximumSize) {
				res.setErrorCode(1);
				res.setErrorMsg("文件不存在");
				return res;
			}
			String uploadFileName = multipartfile.getOriginalFilename();
			System.out.println("uploadFileName: " + uploadFileName);
			OutputStream fos = null;
			InputStream fis = null;
			// 获取扩展名
			String suffix = getExtention(uploadFileName);
			// 保存的文件名
			String targetFilename = UtilDate.getOrderNo() + suffix;
			System.out.println("temp: " + temp + "   " + targetFilename);
			String tmpPath = temp + targetFilename;
			System.out.println("tmpPath: " + tmpPath);
			// copy to temp path
			try {

				fis = multipartfile.getInputStream();
				fos = new FileOutputStream(tmpPath);

				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
			} catch (Exception e) {
				e.printStackTrace();
				res.setErrorCode(1);
				res.setErrorMsg("转换图片异常");
				return res;
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			// 将要缩放图片的原始路径
			String savePath = uploadPath + targetFilename;
			System.out.println("type: " + type);
			System.out.println("savePath: " + savePath);
			if (type.equals("scroll")) {
				GraphicsMagickUtil.zoomImage(640, 400, tmpPath, savePath);
			} else if (type.equals("wxAd")) {
				savePath = adPath + "wx/" + targetFilename;
				GraphicsMagickUtil.scaleImage(640, 400, tmpPath, savePath);
			} else if (type.equals("ad")) {
				GraphicsMagickUtil.scaleImage(640, 400, tmpPath, savePath);
			} else if (type.equals("pc")) {
				if (pcType == -1) {
					// 背景图片
					ImageUtil.scaleWXImage(1024, 768, tmpPath, savePath);
				} else {
					ImageUtil.scaleWXImage(640, 400, tmpPath, savePath);
				}
			} else if (type.equals("XL")) {
				File wxFile = new File(tmpPath);
				wxFile.renameTo(new File(savePath));
			} else {
				// 新的微信广告
				ImageUtil.scaleWXImage(640, 400, tmpPath, savePath);
			}
			path = targetFilename;
			// 删除临时文件
			File temFile = new File(tmpPath);
			if (temFile.isFile() && temFile.exists()) {
				temFile.delete();
			}
			res.put("path", path);
			res.put("pcType", pcType);
			res.put("type", type);
			res.put("uploadFileName", uploadFileName);
		} catch (Exception e) {
			e.printStackTrace();
			res.setErrorCode(1);
			res.setErrorMsg("转换图片异常");
			return res;
		}

		return res;
	}

	private String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	@Override
	public RestResult addUDImage(ImageUploadInfo imageUploadInfo, Long userId) {
		RestResult res = new RestResult();
		String picName = imageUploadInfo.getPicName();
		// int originH=imageUploadInfo.getOriginH();
		// int originW=imageUploadInfo.getOriginW();
		// int height=imageUploadInfo.getHeight();
		// int width=imageUploadInfo.getWidth();
		// int startX=imageUploadInfo.getStartX();
		// int startY=imageUploadInfo.getStartY();
		try {
			if (picName == null || picName.trim().length() == 0
			// || originH < 0
			// || originW < 0 || height < 0 || width < 0 || startX < 0
			// || startY < 0
			) {
				res.setErrorCode(1);
				res.setErrorMsg("参数错误");
				return res;
			}
			// 图片是由上传得到的，图片原本是存在upload路径下，需要生成新的图片到ad路径下
			// if (originH != height || originW != width) {
			// if (startX + width <= originW && startY + height <= originH) {
			// String originPath = uploadPath + picName;
			// File file = new File(originPath);
			// if (file.exists()) {
			// String suffix = getExtention(picName);
			// String name = UtilDate.getOrderNo() + suffix;
			// String savePath = adPath + name;
			// ImageUtil.cutImage(startX, width, startY, height,
			// originPath, savePath);
			// file.delete();
			// picName = name;
			// } else {
			// originPath = adPath + picName;
			// file = new File(originPath);
			// if (file.exists()) {
			// String suffix = getExtention(picName);
			// String name = UtilDate.getOrderNo() + suffix;
			// String savePath = adPath + name;
			// ImageUtil.cutImage(startX, width, startY, height,
			// originPath, savePath);
			// file.delete();
			// picName = name;
			// } else {
			// res.setErrorCode(1);
			// res.setErrorMsg("addUDImage file error ");
			// return res;
			// }
			// }
			// } else {
			// res.setErrorCode(1);
			// res.setErrorMsg("addUDImage param mm error");
			// return res;
			// }
			// } else {
			// 图片没有裁剪，直接复制到ad目录下
			copyFile(new File(uploadPath + picName), new File(adPath + picName));
			new File(uploadPath + picName).delete();
			// }
			BufferedImage bi = ImageUtil.readImage(adPath + picName);
			Ad ad = new Ad();
			ad.setUserId(userId);
			ad.setCreateTime(new Timestamp(System.currentTimeMillis()));
			ad.setLink(imageUploadInfo.getLink());
			ad.setStatus((byte) 1);
			ad.setPath(picName);
			ad.setType((byte) 1);
			ad.setWidth(bi.getWidth());
			ad.setHeight(bi.getHeight());
			adMapper.addAd(ad);
			res.put("adId", ad.getId());
			res.put("picName", picName);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			res.setErrorCode(1);
			res.setErrorMsg("addUDImage exception");
			return res;
		}
	}

	@Override
	public RestResult savePage(Long mainId, String loginContent, String successContent, String pcLoginContent,
			String pcSuccessContent, int type, String action, String pageTitle, String pageName, Long userId) {
		RestResult res = new RestResult();
		if (loginContent.length() == 0 || pcLoginContent.length() == 0 || pcSuccessContent.length() == 0
				|| successContent.length() == 0 || type == 0) {
			res.setErrorCode(1);
			res.setErrorMsg("参数错误");
			return res;
		}
		if (action != null && action.equals("new")) {// 新建认证页面
			if (pageTitle == null || pageTitle.trim().length() == 0) {
				res.setErrorCode(1);
				res.setErrorMsg("缺少页面标题");
				return res;
			} else {
				String[] content = new String[] { loginContent, successContent, pcLoginContent, pcSuccessContent };
				res = addUserPage(userId, content, type, pageTitle, pageName);
			}
		} else {// 编辑
			if (mainId < 0 || mainId == null) {
				res.setErrorCode(1);
				res.setErrorMsg("参数错误");
				return res;
			}
			try {
				// 根据pageList_id查找所有的页面page
				List<Page> pageList = authPageMapper.queryPageByPageListId(new ArrayList<Long>() {
					{
						add(mainId);
					}
				});
				if (pageList.size() > 0) {
					for (Page page : pageList) {
						String path = pagePaths + userId + File.separator + page.getPath();
						File file = new File(path);
						if (file.exists()) {
							Document doc = Jsoup.parse(file, "utf-8");
							String headStr = doc.select("head").html();
							if (page.getTmId().equals(10000001L)) {
								doc = Jsoup.parse(loginContent);
							} else if (page.getTmId().equals(10000002L)) {
								doc = Jsoup.parse(successContent);
							} else if (page.getTmId().equals(10000003L)) {
								doc = Jsoup.parse(pcLoginContent);
							} else {
								doc = Jsoup.parse(pcSuccessContent);
							}
							// 删除编辑按钮
							// doc.select(".editor").remove();
							// doc.select(".del").remove();
							Element head = doc.select("head").first();
							head.html(headStr);
							if ((page.getTmId() - 1000000) > 2) {// pc端
								Element body = doc.select("body").first();
								String bodyStr = body.html();
//								body.html("<div id =\"finishPage\" >" + bodyStr + " </div>");
								// doc.select(".eidot").removeClass("ui-draggable");
								// doc.select(".onepic").removeClass("ui-draggable");
							}
							FileOutputStream fos = new FileOutputStream(file, false);
							OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
							osw.write("<!DOCTYPE html>\n" + doc.html());
							osw.close();
							fos.close();

						} else {
							res.setErrorCode(1);
							res.setErrorMsg("页面文件不存在");
							return res;
						}
					}
					PageList pagelist = new PageList();
					pagelist.setName(pageName);
					pagelist.setTitle(pageTitle);
					pagelist.setId(mainId);
					pageListMapper.updateOrder(pagelist);
				} else {
					res.setErrorCode(1);
					res.setErrorMsg("文件不存在");
					return res;
				}
			} catch (Exception e) {
				e.printStackTrace();
				res.setErrorCode(1);
				res.setErrorMsg("加载文件异常");
				return res;
			}
		}
		return res;
	}

	public RestResult addUserPage(Long userId, String[] content, int type, String title, String pageName) {
		RestResult res = new RestResult();
		final String fileName = UtilDate.getOrderNo() + ".htm";
		res = addUserPage(userId, fileName, content, type, title, pageName);
		return res;
	}

	public RestResult addUserPage(Long userId, String fileName, String[] content, int type, String title,
			String pageName) {
		// 1.构建保存页面的路径。按照页面的类型，将页面保存在商家页面路径下的login、success文件夹下。
		// 文件名为UtilDate.getOrderNo()+".htm"
		// 2.保存页面内容
		// 3.将页面信息保存到page表中
		RestResult res = new RestResult();
		String dir = "";
		String destP = "";
		File destF = null;
		String dirs[] = new String[4];
		Document doc = null;
		String temp = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
				+ "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no\"><meta name=\"format-detection\" content=\"telephone=no\">"
				+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/a.css\">"
				+ "<script type=\"text/javascript\" src=\"../js/jquery.min.js\"></script>"
				+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/stylewx.css\">"
				+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/public.css\">"
				+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/flexslider.css\">"
				+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/page_v1.2.css\">"
				+ "<script type=\"text/javascript\" src=\"../js/jquery.flexslider-min.js\"></script>";
		// + "<script type=\"text/javascript\"
		// src=\"../js/wxphone.js\"></script>";
		for (int i = 0; i < 4; i++) {
			switch (i + 1) {
			case 1:// 手机登录页面
				dir = "login/";
				break;
			case 2://
				dir = "success/";
				break;
			case 3:// PC登录页面
				dir = "pclogin/";
				break;
			case 4://
				dir = "pcsuccess/";
				break;
			}

			destP = pagePaths + userId + File.separator + dir;
			destF = new File(destP);
			if (!destF.exists()) {
				destF.mkdirs();
			}
			dir += fileName;
			destP += fileName;
			dirs[i] = dir;
			Element body = null;
			String bodyStr = "";
			doc = Jsoup.parse(content[i]);
			Element head = doc.select("head").first();
			switch (i + 1) {
			case 1:// 手机登录页面
				head.html(
						"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=0.65,maximum-scale=1,minimum-scale=0.65,user-scalable=no\"><meta name=\"format-detection\" content=\"telephone=no\">"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/a.css\">"
								+ "<script type=\"text/javascript\" src=\"../js/jquery.min.js\"></script>"
								+ "<script type=\"text/javascript\" src=\"../js/ft-carousel.min.js\"></script>"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/stylewx.css\">"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/public.css\">"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/flexslider.css\">"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/page_v1.2.css\">"
								+ "<script type=\"text/javascript\" src=\"../js/jquery.flexslider-min.js\"></script>"
								+ "<script type=\"text/javascript\" src=\"../js/wxphone.js\"></script>"
								+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/media_queries_v1.3.css\">"
								+ "<script type=\"text/javascript\" src=\"../js/auth.js\"></script>"
								+ "<script type=\"text/javascript\" src=\"../js/sha256.js\"></script>"
								+ "<script type=\"text/javascript\" src=\"../js/a.js\"></script><title>"
								+ title
								+ "</title>");
				break;
			case 2://
				head.html(temp 
						+ "<script type=\"text/javascript\" src=\"../js/successtips.js\"></script>"
						+"<script type=\"text/javascript\" src=\"../js/a.js\"></script>" + "<title>" + title
						+ "</title>");
				break;
			case 3:// PC登录页面
				head.html(temp 
						 + "<script type=\"text/javascript\" src=\"../js/sha256.js\"></script>"
						 + "<script type=\"text/javascript\" src=\"../js/b.js\"></script>"
						 + "<title>" + title + "</title>");
				body = doc.select("body").first();
				bodyStr = body.html();
//				body.html("<div id =\"finishPage\" >" + bodyStr + " </div>");
				break;
			case 4://
				head.html(temp 
						+ "<script type=\"text/javascript\" src=\"../js/successtips.js\"></script>"
						+ "<script type=\"text/javascript\" src=\"../js/b.js\"></script>" + "<title>" + title
						+ "</title>");
				body = doc.select("body").first();
				bodyStr = body.html();
//				body.html("<div id =\"finishPage\" >" + bodyStr + " </div>");
				break;
			default:
				head.html(temp + "<title>" + title + "</title>");
			}
			try {
				FileOutputStream fos = new FileOutputStream(destP, false);
				OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
				osw.write("<!DOCTYPE html>\n" + doc.html());
				osw.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
				res.setErrorCode(1);
				res.setErrorMsg("文件写入异常");
				return res;
			}
		}

		PageList pagelist = new PageList();
		pagelist.setUserId(userId);
		pagelist.setName(pageName);
		pagelist.setTitle(title);
		pageListMapper.save(pagelist);
		for (int i = 0; i < 4; i++) {
			Page page = new Page();
			page.setPath(dirs[i]);
			page.setTmId((long) (10000000 + i + 1));
			page.setPageListId(pagelist.getId());
			authPageMapper.save(page);
		}
		return res;
	}

	@Override
	public List<PageList> queryAll(Long userId) {
		return pageListMapper.queryAll(userId);
	}

}
